<template>
	<!-- 模板中根元素只能有一个 -->
	<div>
		<van-form @submit="onSubmit">
			<!-- 只读设置 readonly-->
			<van-field label="编号" v-model="userForm.id" readonly> </van-field>
			<van-field label="用户" v-model="userForm.name" readonly />
			
			<!-- 输入原来密码，新密码 确认密码 -->
			<van-field label="原来密码" v-model="userForm.password" type="password" placeholder="请输入原密码"
				:rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]" />
			<van-field label="新的密码" v-model="userForm.password2" type="password" placeholder="请输入新密码"
				:rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]" />
			<van-field label="确认密码" v-model="userForm.password22" type="password" placeholder="请输入新密码"
				:rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]" />

			<!-- 提交按钮 -->
			<div style="margin: 16px;">
				<van-button round block type="info" native-type="submit">提交</van-button>
			</div>
		</van-form>
	</div>
</template>

<script>
	//导入密码修改接口
	import {
		updatePwdAPI,
	} from "@/api/user.js";

	//导入本地存储工具-获取用户信息
	import {
		getUserLocal
	} from "@/utils/auth.js";

	export default {
		data() {
			return {
				userForm: {
					id: null,
					name: "",
					password: "",//原密码
					password2: "", //新的密码
					password22: "", //确认密码 
				},

				//用户名及密码验证规则:字母数字‘6~12
				regNamePwd: /^[a-z0-9]{3,12}$/i,
			};
		},
		
		//生命周期函数
		mounted() {
			let user = getUserLocal();
			this.userForm.id = user.id;
			this.userForm.name = user.name;
		},


		methods: {

			//处理提交保存
			onSubmit() {
				
				if (this.userForm.password2 != this.userForm.password22) {
					this.$toast("确认密码两次输入不一致");
					return;
				}

				//注意传递过去的参数user的属性名
				let user = this.userForm;
				delete user.password22; //删除该临时的字段
				updatePwdAPI(user).then(() => {
					this.$toast("密码更改成功！");
					//延时1秒跳转
					setTimeout(()=>{
						this.$router.push({
							name: "user"
						});
					},1000);
				});
			},
		},
	};
</script>



<style lang="less" scoped>

</style>
